/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package outToR;

import db.HivDbIntegration.IntersectionSummary;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import units.CellType;
import units.DifferentialExpression;
import units.DifferentialExpressionLibrary;
import units.ExpressionLibrary;
import units.DiseaseStage;
import units.Gene;
import units.GeneLibrary;
import units.MonkeyType;
import units.Sample;
import utils.FileUtils;
import utils.Handle;

/**
 *
 * @author jamie
 */
public class OutputForMinet {

    private File outFolder = new File("/Users/jamie/Dropbox/monkeys/outputForR/minet/");
    private IntersectionSummary intersectionSummary;
    private GeneLibrary geneLibrary;
    private ExpressionLibrary expressionLibrary;
    private Set<Sample> samples;
    private TreeMap<Integer, List<DifferentialExpression>> differentiallyExpressedGenes;

    public OutputForMinet() {

        geneLibrary = new GeneLibrary();
        DifferentialExpressionLibrary del = new DifferentialExpressionLibrary();
        del = new DifferentialExpressionLibrary();
        del.populateForAllMonkeyTypes(geneLibrary);

        expressionLibrary = new ExpressionLibrary();
        expressionLibrary.populateForAllSamples(geneLibrary);
        samples = expressionLibrary.getAllSamples();
        geneLibrary.populateGeneSymbols();
        intersectionSummary = new IntersectionSummary();
        Integer[] timePoints = {1, 6, 14, 28,41, 65,115};
        differentiallyExpressedGenes = del.getDifferentialExpressedGenes(MonkeyType.A, CellType.P, timePoints, 0.1);
        try {
//            output(MonkeyType.A, timePoints);
//            output(MonkeyType.M, timePoints);
//            output(MonkeyType.A, CellType.L, timePoints);
//            output(MonkeyType.A, CellType.P, timePoints);
//            output(MonkeyType.M, CellType.L, timePoints);
            output(MonkeyType.A, CellType.P, timePoints);
        } catch (IOException ex) {
            Logger.getLogger(OutputForMinet.class.getName()).log(Level.SEVERE, null, ex);
        }


//        for (MonkeyType mt : MonkeyType.values()) {
//            for (DiseaseStage ds : DiseaseStage.values()) {
//                if (!ds.equals(DiseaseStage.POST)) {
//                    try {
//                        output(mt, ds);
//                    } catch (IOException ex) {
//                        Logger.getLogger(OutputForMinet.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//                }
//            }
//        }


    }

    private void output(MonkeyType monkeyType, Integer[] timePoints) throws IOException {
        List<Integer> probeList = intersectionSummary.getMultiArrayClusterProbes(monkeyType);
        Collections.sort(probeList);
        TreeMap<String, List<Double>> expression = getExpression(monkeyType, timePoints, probeList);
        File out = new File(outFolder, monkeyType + "_select.txt");
        BufferedWriter writer = FileUtils.getBufferedWriter(out);
        StringBuffer buffer = new StringBuffer();

        for (Integer probeId : probeList) {
            if (differentiallyExpressedGenes.containsKey(probeId)) {
                buffer.append(probeId + "\t");
            }
        }
        writer.append(buffer.toString().trim() + "\n");
        for (String array : expression.keySet()) {
            buffer = new StringBuffer();
            buffer.append(array + "\t");
            for (double exp : expression.get(array)) {
                buffer.append(exp + "\t");
            }
            writer.append(buffer.toString().trim() + "\n");
        }
        writer.close();
    }

    private void output(MonkeyType monkeyType, CellType ct, Integer[] timePoints) throws IOException {
        List<Integer> probeList = intersectionSummary.getMultiArrayClusterProbes(monkeyType, ct);
        Collections.sort(probeList);
        TreeMap<String, List<Double>> expression = getExpression(monkeyType, ct, timePoints, probeList);
        File out = new File(outFolder, monkeyType.name() + ct.name() + "_select.txt");
        BufferedWriter writer = FileUtils.getBufferedWriter(out);
        StringBuffer buffer = new StringBuffer();

        for (Integer probeId : probeList) {
            if (differentiallyExpressedGenes.containsKey(probeId)) {
                buffer.append(probeId + "\t");
            }
        }
        writer.append(buffer.toString().trim() + "\n");
        for (String array : expression.keySet()) {
            if (expression.get(array).size() > 0) {
                buffer = new StringBuffer();
                buffer.append(array + "\t");
                for (double exp : expression.get(array)) {
                    buffer.append(exp + "\t");
                }
                writer.append(buffer.toString().trim() + "\n");
            }
        }
        writer.close();
    }

    private TreeMap<String, List<Double>> getExpression(MonkeyType monkeyType, Integer[] timePoints, List<Integer> probeList) {
        TreeMap<String, List<Double>> expression = new TreeMap<String, List<Double>>();
        for (Sample s : samples) {
            if (s.getMonkeyType().equals(monkeyType)) {
                for (int timePoint : timePoints) {

                    String key = s.getSampleName() + "_" + timePoint;
                    if (!expression.containsKey(key)) {
                        expression.put(key, new ArrayList<Double>());
                    }
                    for (Integer probeId : probeList) {
                        if (differentiallyExpressedGenes.containsKey(probeId)) {
                            double exp = 0;
                            try {
                                exp = expressionLibrary.getExpression(probeId, s, timePoint).getLogExp();

                            } catch (Exception e) {
                                System.out.println(probeId + ", " + s.getSampleName() + ", " + timePoint);
                            }
                            expression.get(key).add(exp);
                        }
                    }

                }
            }
        }
        return expression;
    }

    private TreeMap<String, List<Double>> getExpression(MonkeyType monkeyType, CellType ct, Integer[] timePoints, List<Integer> probeList) {
        TreeMap<String, List<Double>> expression = new TreeMap<String, List<Double>>();
        for (Sample s : samples) {
            if (s.getMonkeyType().equals(monkeyType) && s.getCellType().equals(ct)) {
                for (int timePoint : timePoints) {

                    String key = s.getSampleName() + "_" + timePoint;
                    if (!expression.containsKey(key)) {
                        expression.put(key, new ArrayList<Double>());
                    }
                    for (Integer probeId : probeList) {
                        if (differentiallyExpressedGenes.containsKey(probeId)) {
                            double exp = 0;
                            try {
                                exp = expressionLibrary.getExpression(probeId, s, timePoint).getLogExp();
                                expression.get(key).add(exp);
                            } catch (Exception e) {
                                System.out.println(probeId + ", " + s.getSampleName() + ", " + s.getId() + "\t" + timePoint);
                            }



                        }
                    }

                }
            }
        }
        return expression;
    }
//    private void output(MonkeyType monkeyType, DiseaseStage diseaseStage) throws IOException {
//        List<Integer> probeList = intersectionSummary.getMultiArrayProbes(geneLibrary);
//        Collections.sort(probeList);
//        TreeMap<String, List<Double>> expression = getExpression(monkeyType, diseaseStage, probeList);
//        File out = new File(outFolder, monkeyType + "_" + diseaseStage + ".txt");
//        BufferedWriter writer = FileUtils.getBufferedWriter(out);
//        StringBuffer buffer = new StringBuffer();
//        for (int probeId : probeList) {
//            buffer.append(probeId + "\t");
//        }
//        writer.append(buffer.toString().trim() + "\n");
//        for (String array : expression.keySet()) {
//            buffer = new StringBuffer();
//            buffer.append(array + "\t");
//            for (double exp : expression.get(array)) {
//                buffer.append(exp + "\t");
//            }
//            writer.append(buffer.toString().trim() + "\n");
//        }
//        writer.close();
//
//
//    }
//
//    private TreeMap<String, List<Double>> getExpression(MonkeyType monkeyType, DiseaseStage diseaseStage, List<Integer> probeList) {
//        TreeMap<String, List<Double>> expression = new TreeMap<String, List<Double>>();
//        for (Sample s : samples) {
//            if (s.getMonkeyType().equals(monkeyType)) {
//                for (int timePoint : s.getTimePoints()) {
//                    if (diseaseStage.hasStage(timePoint)) {
//                        String key = s.getSampleName() + "_" + timePoint;
//                        if (!expression.containsKey(key)) {
//                            expression.put(key, new ArrayList<Double>());
//                        }
//                        for (Gene g : geneList) {
//                            double exp = 0;
//                            try {
//                                exp = expressionLibrary.getExpression(g, s, timePoint).getLogExp();
//
//                            } catch (Exception e) {
//                                System.out.println(g.getId() + ", " + s.getSampleName() + ", " + timePoint);
//                            }
//                            expression.get(key).add(exp);
//                        }
//                    }
//                }
//            }
//        }
//        return expression;
//    }
}


